<template>
  <BaseMainSlot>
    <!-- 这页面 -->
    <template v-slot:zhactbar>
      <ActionBar
        :page-no="100"
        :add-active="addActive"
        :del-active="delActive"
        :cancel-active="cancelActive"
        :has-edit="false"
        :has-del="false"
        :has-save="false"
        :save-active="saveActive"
        :has-fasong="true"
        fasong-text="agriculture"
        @fasong="examine"
        @add="add"
        @cancel="cancel"
        @del="del"
      />
      <!-- <el-button
        class="examine"
        @click="examine"
      > 原料提交 </el-button> -->
    </template>
    <template v-slot:boxleft>
      <div class="zhtabletitle" style="margin: 15px 0px">已有原料</div>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        stripe
        border
        height="calc(100% - 90px)"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column
          v-for="(item, index) in formDatalists"
          :key="index"
          :prop="item.prop"
          :label="item.name"
          min-width="110"
          :column-key="`${item.prop}`"
        >
          <template
            v-if="scope.row[`materialNo`] !== undefined"
            slot-scope="scope"
          >
            <span v-if="item.prop === 'enableStatus'">{{
              scope.row[item.prop] ? "是" : "否"
            }}</span>
            <span v-else>{{ scope.row[item.prop] || "" }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100" label="操作">
          <template v-if="scope.row.materialNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(100, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              style="height: 10px"
              @click="handleDelete(scope.row.materialNo)"
              ><i class="el-icon-delete"></i> 删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:boxright>
      <div class="zhtabletitle">
        所有原料
        <el-input
          v-model="materialName"
          class="w50p"
          style="margin: 0 10px; width: 30%"
          placeholder="搜索原料名称"
          clearable
          @input="searchTwo"
        />
        <!-- <el-select
          v-model="materialTypeNo"
          filterable
          clearable
          placeholder="搜索原料类型"
          @change="searchTwo"
        >
          <el-option
            v-for="(item, index) in materialTypeList"
            :key="index"
            :label="item.materialTypeName"
            :value="item.materialTypeNo"
          />
        </el-select> -->
        <el-cascader
          placeholder="搜索原料类型"
          v-model="cascaderValue"
          :options="cascaderList"
          :props="{value:'materialTypeNo', label: 'materialTypeName', children: 'child', multiple: false, checkStrictly: true}"
          @change="handleChange"
          :clearable="true"
        ></el-cascader>
      </div>
      <el-table
        v-loading="loadingtwo"
        highlight-current-row
        :data="tableDatatwo"
        stripe
        border
        height="calc(100% - 90px)"
        @selection-change="handleSelectionChangetwo"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column
          v-for="(item, index) in formDatalists"
          :key="index"
          :prop="item.prop"
          :label="item.name"
          min-width="110"
          :column-key="`${item.prop}`"
        >
          <template
            v-if="scope.row[`materialNo`] !== undefined"
            slot-scope="scope"
          >
            <span v-if="item.prop === 'enableStatus'">{{
              scope.row[item.prop] ? "是" : "否"
            }}</span>
            <span v-else>{{ scope.row[item.prop] || "" }}</span>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSizetwo"
        :current-page="currentPagetwo"
        :total-size="totalSizetwo"
        @changePageSize="changePageSizetwo"
        @changeCurrentPage="changeCurrentPagetwo"
      />
    </template>

    <template v-slot:dig>
      <!-- 新增业务组件的弹框 -->
      <dialogds
        title="原料"
        :visible="dialogExamineFormVisible"
        @close="close"
        @titlebtn="titlebtn"
      >
        <template v-slot:form>
          <el-form
            ref="ExamineForm"
            label-position="left"
            :model="ExamineForm"
            class="el-form"
          >
            <el-form-item
              v-for="(item, index) in formDatalists"
              :key="index"
              :label="item.name + ':'"
              :prop="item.type === 'Select' ? item.selectValue : item.prop"
              class="w50p"
              :rules="
                item.isCheck
                  ? rules[item.prop]
                  : [
                      {
                        required: item.required,
                        message: item.name + '不能为空',
                        trigger: ['blur', 'change'],
                      },
                    ]
              "
            >
              <el-input
                v-if="item.type === 'input'"
                v-model="ExamineForm[`${item.prop}`]"
                :placeholder="'请输入' + item.name"
                clearable
              />
              <el-select
                v-if="item.type === 'Select'"
                v-model="ExamineForm[item.selectValue]"
                filterable
                :placeholder="'请选择' + item.name"
                clearable
              >
                <el-option
                  v-for="(items, indexs) in item.typeObj.list"
                  :key="indexs"
                  :label="items.name"
                  :value="items.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </template>
        <template v-slot:btn>
          <el-button class="zh-button-two" type="primary" @click="savemes"
            >提 交</el-button
          >
        </template>
        <template v-slot:table>
          <el-input
            v-model="esname"
            style="margin-bottom: 10px; width: 30%"
            placeholder="输入名称查询"
            clearable
            @input="titlebtn(2)"
          />
          <el-table
            class="examineTable"
            highlight-current-row
            :data="ExamineTable"
            stripe
            border
            height="calc(100% - 90px)"
          >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column
              v-for="(item, index) in formDatalists"
              :key="index"
              :prop="item.prop"
              :label="item.name"
              min-width="110"
            >
              <template slot-scope="scope">
                <span v-if="item.prop === 'enableStatus'">{{
                  scope.row[item.prop] ? "是" : "否"
                }}</span>
                <span v-else>{{ scope.row[item.prop] || "" }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="原因" min-width="90">
              <template slot-scope="scope">
                {{ scope.row.reason || "————" }}
              </template>
            </el-table-column>
            <el-table-column prop="applyStatus" label="状态">
              <template slot-scope="scope">
                <span
                  v-if="scope.row.applyStatus === 1"
                  style="color: yellow; font-weight: 600"
                >
                  审核中</span
                >
                <span
                  v-if="scope.row.applyStatus === 0"
                  style="color: green; font-weight: 600"
                >
                  通过</span
                >
                <span
                  v-if="scope.row.applyStatus === 2"
                  style="color: red; font-weight: 600"
                >
                  审核不通过</span
                >
              </template>
            </el-table-column>
            <el-table-column width="120" label="操作">
              <template slot-scope="scope">
                <el-button
                  class="text-btn-cursor"
                  type="text"
                  :disabled="scope.row.applyStatus !== 1"
                  size="small"
                  style="height: 15px"
                  @click="Examineedit(scope.row)"
                  ><i class="el-icon-edit-outline"></i>修 改</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
      </dialogds>
      <el-dialog title="提示" :visible.sync="dialogExaminesVisible" width="58%">
        <el-form
          ref="ExamineForms"
          label-position="left"
          :model="ExamineForms"
          class="el-form"
        >
          <el-form-item
            v-for="(item, index) in formDatalists"
            :key="index"
            :label="item.name + ':'"
            :prop="item.type === 'Select' ? item.selectValue : item.prop"
            class="w50p"
            :rules="
              item.isCheck
                ? rules[item.prop]
                : [
                    {
                      required: item.required,
                      message: item.name + '不能为空',
                      trigger: ['blur', 'change'],
                    },
                  ]
            "
          >
            <el-input
              v-if="item.type === 'input'"
              v-model="ExamineForms[`${item.prop}`]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <el-select
              v-if="item.type === 'Select'"
              v-model="ExamineForms[item.selectValue]"
              filterable
              :placeholder="'请选择' + item.name"
              clearable
            >
              <el-option
                v-for="(items, indexs) in item.typeObj.list"
                :key="indexs"
                :label="items.name"
                :value="items.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button
            class="zh-button-one"
            @click="dialogExaminesVisible = false"
            >取 消</el-button
          >
          <el-button class="zh-button-two" type="primary" @click="savees"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
<script>
import ActionBar from "@/components/ActionBar/index";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/basic-info-manage/agr-source-base-Manage";
import nowunit from "@/api/basic-info-manage/unit-manage/index.js";
import nowType from "@/api/basic-info-manage/agr-source-Type-Manage/index.js";
import dialogds from "../component/dialog.vue";
import BaseMainSlot from "@/components/BaseMainSlot/basezuoyou.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
// import { getToken } from '@/utils/auth';
export default {
  name: "AgrSourceBaseManage",
  components: { ActionBar, Pagination, BaseMainSlot, dialogds },
  mixins: [mymixin],
  data() {
    return {
      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "materialName",
          typeObj: {},
          name: "原料名称",
          required: true,
        },
        {
          type: "input",
          prop: "materialShortName",
          typeObj: {},
          name: "原料简称",
          // required: true
        },
        {
          type: "Select",
          prop: "materialTypeName",
          selectValue: "materialTypeNo",
          typeObj: {},
          name: "原料类型名称",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "brand",
          typeObj: {},
          name: "品牌",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "materialbarCode",
          typeObj: {},
          name: "条形码",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "materialmnecode",
          typeObj: {},
          name: "助记码",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "materialspec",
          typeObj: {},
          name: "规格",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "model",
          typeObj: {},
          name: "型号",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "version",
          typeObj: {},
          name: "版本",
          isCheck: true,
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "prodarea",
          typeObj: {},
          name: "产地",
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "productor",
          typeObj: {},
          name: "生产厂家",
          // required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "unitName",
          selectValue: "unitNo",
          typeObj: {},
          name: "主计量单位",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "unitvolume",
          typeObj: {},
          name: "单位体积/L",
          isCheck: true,
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "unitweight",
          typeObj: {},
          name: "单位重量/kg",
          isCheck: true,
          // required: true
        },
        {
          type: "Select", // input Select Checkbox TimePicker
          prop: "enableStatus",
          selectValue: "enableStatus",
          typeObj: {
            list: [
              { name: "否", value: 0 },
              { name: "是", value: 1 },
            ],
          },
          name: "是否启用",
          isCheck: true,
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {},
          name: "备注",
          notSearch: true,
        },
      ],
      // ----表格二号----
      loadingtwo: true,
      // 当前页
      currentPagetwo: 1,
      // 每页的数据条数
      pageSizetwo: 10,
      // 总条数
      totalSizetwo: 0,
      tableData: [],
      // 表格二号数据
      tableDatatwo: [],
      // 是否能输入
      // -------
      canInput: false,
      rules: {},
      // 选中的数据项数组 employeeId组成 (此数组最多为一个)
      nowselectedList: [],
      materialList: [],
      materialTypeList: [],
      materialTypeNo: undefined,
      materialName: undefined,
      dialogExamineFormVisible: false,
      unitList: [],
      unitLists: [],
      unitTypeList: [],
      dialogExaminesVisible: false,
      ExamineForms: {},
      cascaderList: [],
      cascaderValue: [],
      cascaderLists: []
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
    // 获取表格数据
    this.getSelect();
  },
  mounted() {
    this.getTableDataListone();
  },
  methods: {
    examine() {
      this.dialogExamineFormVisible = true;
      // this.$refs['ExamineForm'].resetFields();
    },
    searchTwo() {
      this.currentPagetwo = 1;
      this.getTableDataListtwo();
    },
    savemes() {
      this.$refs["ExamineForm"].validate((valid) => {
        if (valid) {
          let param = {
            ...this.ExamineForm,
            applyStatus: 1,
            organizationNo: sessionStorage.organizationNo,
            farming: 'PLANT',
            rawType: true
          };
          nowpagereq.addListES(param).then((response) => {
            let mes = response;
            if (mes.code === 1) {
              this.$message.success("提交成功！");
              this.ExamineForm = {};
              this.$refs["ExamineForm"].resetFields();
              // this.gettabledataList()
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    Examineedit(e) {
      this.ExamineForms = { ...e };
      this.dialogExaminesVisible = true;
    },
    savees() {
      this.$refs["ExamineForms"].validate((valid) => {
        if (valid) {
          let param = {
            ...this.ExamineForms,
            farming: 'PLANT',
            rawType: true
          };
          nowpagereq.editListES(param).then((response) => {
            let mes = response;
            if (mes.code === 1) {
              this.$message.success("修改成功！");
              this.ExamineForms = {};
              this.$refs["ExamineForms"].resetFields();
              this.dialogExaminesVisible = false;
              // this.gettabledataList()
              this.titlebtn(2);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    close(e) {
      this.dialogExamineFormVisible = e;
    },
    titlebtn(e) {
      if (e === 2) {
        let params = {
          page: this.currentPage,
          size: this.pageSize,
          entity: {
            unitTypeNo: this.unitTypeNo,
            unitName: this.unitName,
          },
          materialName: this.esname,
          farming: 'PLANT',
          rawType: true
        };
        nowpagereq.getListES(params).then((response) => {
          let mes = response.data;
          if (response.code === 1) {
            this.ExamineTable = mes;
            this.resetActionBar();
          } else {
            this.$message.warning("获取表格失败");
          }
        });
      }
    },
    // 获取当前拥有类型表格
    getTableDataListone() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          rawType: true
        }
      };
      nowpagereq.getFarmingAssetList(params).then((res) => {
        this.loading = false;
        if (res.code === 0) {
          this.$message.error("当前原料表格获取失败");
        }
        let data = res.data;
        // 赋值总条数
        this.totalSize = data.totalElements;
        // 赋值数组
        this.tableData = data.content;
        this.addblankmet();
        this.resetActionBar();
        this.addActive = false;
      });
    },
    // 获取所有原料表格
    getTableDataListtwo(dataItemIdList) {
      this.loadingtwo = true;
      nowpagereq
        .getAllBasicList({
          page: this.currentPagetwo,
          size: this.pageSizetwo,
          entity: {
            materialTypeNo: this.materialTypeNo,
            materialName: this.materialName,
            materialTypeNoList: dataItemIdList,
            farming: 'PLANT',
            rawType: true
          },
        })
        .then((res) => {
          this.loadingtwo = false;
          if (res.code === 0) {
            this.$message.error("所有原料表格获取失败");
          }
          let data = res.data;
          // 赋值总条数
          this.totalSizetwo = data.totalElements;
          // 赋值数组
          this.tableDatatwo = data.content;

          let havline = this.tableDatatwo.length % this.pageSizetwo;
          if (this.tableDatatwo.length < this.pageSizetwo) {
            if (havline < this.pageSizetwo) {
              const remain = this.pageSizetwo - havline;
              for (var i = 0; i < remain; i++) {
                this.tableDatatwo.push({
                  indflag: i + this.tableDatatwo.length - 1,
                });
              }
            }
          }

          this.resetActionBar();
          this.addActive = false;
        });
    },
    handleChange(value) {
      console.log(value,'eee',this.cascaderLists);
      this.currentPagetwo = 1;
      if(value.length === 0) {
        this.getTableDataListtwo(this.cascaderLists)
      } else {
        this.getTableDataListtwo(value)
      }
    },
    treeFn(tree,func) {
      tree.forEach(node=>{
        func(node)
        node.child && this.treeFn(node.child,func)
      })
    },
    async getSelect() {
      let result = await nowpagereq.getFarmingAssetLists({ rawType: true });
      this.cascaderList = result.data;
      this.cascaderLists = []
      this.treeFn(this.cascaderList,(node)=>{
        this.cascaderLists.push(node.materialTypeNo)
        if(node.child.length === 0) {
          delete node.child
        }
      })
      this.getTableDataListtwo(this.cascaderLists)
      const { data: res } = await nowpagereq.getAllBList({});
      this.materialList = res;
      let arr = [];
      res.forEach((element) => {
        arr.push({
          materialTypeName: element.materialTypeName,
          materialTypeNo: element.materialTypeNo,
        });
      });

      let map = new Map();
      for (let item of arr) {
        if (!map.has(item.materialTypeNo)) {
          map.set(item.materialTypeNo, item);
        }
      }
      this.materialTypeList = [...map.values()];

      // 获取原料类型
      const { data: ress } = await nowType.queryByCondition({ rawType: true });
      this.unitTypeList = ress;
      // 获取数量单位
      const { data: Unit } = await nowunit.getallunitlist({
        // unitTypeNo: "1001491616960118784"
      });
      this.unitList = Unit;
      this.formDatalists.forEach((item, index) => {
        if (item.prop === "materialTypeName") {
          let list = ress.map((el) => {
            return { name: el.materialTypeName, value: el.materialTypeNo };
          });
          this.$set(this.formDatalists[index].typeObj, "list", list);
        }
        if (item.prop === "unitName") {
          let list = Unit.map((el) => {
            return { name: el.unitName, value: el.unitNo };
          });
          this.$set(this.formDatalists[index].typeObj, "list", list);
        }
      });

      // 获取数量单位
      // const { data: Units } = await nowunit.getallunitlist({
      //   unitTypeNo: "995416636939862016"
      // });
      // this.unitLists = Units;
      //   this.materialList = []
      //   let arrs = []
      //   res.forEach(element => {
      //     arrs.push({
      //       text: element.materialName,
      //       value: element.materialNo
      //     })
      //   });

      //   let maps = new Map();
      //   for (let item of arrs) {
      //     if (!maps.has(item.value)) {
      //       maps.set(item.value, item);
      //     }
      //   }
      //   this.materialList = [...maps.values()];
      // },
      // filterTag(value, row) {
      //   return row.materialTypeNo === value;
      // },
      // filterTags(value, row) {
      //   return row.materialNo === value;
    },
    search() {
      this.currentPage = 1;
      this.getTableDataListone();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataListone();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataListone();
    },
    changePageSizetwo(pageSize) {
      this.pageSizetwo = pageSize;
      this.getTableDataListtwo();
    },
    changeCurrentPagetwo(currentPage) {
      this.currentPagetwo = currentPage;
      this.getTableDataListtwo();
    },
    handleSelectionChange(list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map((item) => {
        return item.id;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    handleSelectionChangetwo(list) {
      this.nowselectedTwoList = [];
      // this.nowselectedTwoList = list.map(item => {
      //   return item.materialNo;
      // });
      let lists = list.map((item) => {
        if (item.materialNo) {
          return item.materialNo;
        } else {
          return "";
        }
        // return {
        //   'description': item.description,
        //   'unitNo': item.unitNo,
        //   'unitTypeName': item.unitTypeName,
        //   'unitTypeNo': item.unitTypeNo,
        //   'symbol': item.symbol,
        //   'basicRatio': item.basicRatio,
        //   'organizationNo': sessionStorage.getItem('organizationNo') }
      });
      var r = lists.filter(function (s) {
        return s && s.trim(); // 注：IE9(不包含IE9)以下的版本没有trim()方法
      });
      this.nowselectedTwoList = r;
      if (this.nowselectedTwoList && this.nowselectedTwoList.length > 0) {
        this.addActive = true;
      } else this.addActive = false;
    },
    handleDelete(no) {
      this.$confirm("是否删除原料？", "删除原料", {
        distinguishCancelAndClose: true,
        confirmButtonClass: "btnFalses",
        confirmButtonText: "删除",
        cancelButtonText: "取消删除",
      })
        .then(() => {
          nowpagereq.delList([no]).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataListone();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch((action) => {
          // this.$message({
          //   type: 'info',
          //   message: action === 'cancel'
          //     ? '取消删除'
          //     : '停留在当前页面'
          // })
        });
    },
    add() {
      nowpagereq.addList(this.nowselectedTwoList).then((res) => {
        if (res.code === 1) {
          this.getTableDataListone();
          this.$message.success("添加成功");
        } else {
          this.$message.error(res.msg || "添加失败");
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}

.examineTable {
  ::v-deep ::-webkit-scrollbar-thumb {
    width: 6px;
    background: #ccc;
  }
}
// ::v-deep .el-message-box__wrapper {
//       background: red !important;
//   .el-message-box {
//     .btnFalses {
//       background: red !important;
//     }
//   }
// }
</style>
